
package gs.eisenhower.swallet.ui_component;

import gs.eisenhower.swallet.R;
import gs.eisenhower.swallet.adapter.WalletAdapter;
import gs.eisenhower.swallet.dao.BudgetDaoImpl;
import gs.eisenhower.swallet.dao.WalletDaoImpl;
import gs.eisenhower.swallet.model.Wallet;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;

public class HistoryFragment extends Fragment {
	private WalletDaoImpl walletTransaction;
	private BudgetDaoImpl budgetTransaction;
	private WalletAdapter adapter;
	private List<Wallet> transactions;
	private List<String> transactionDates;
	
	 @Override
	 public View onCreateView(LayoutInflater inflater, ViewGroup container,
	                             Bundle savedInstanceState) {
	        return inflater.inflate(R.layout.fragment_history, container, false);
	 }
	 
	@Override
	public void onActivityCreated (Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		
		walletTransaction = new WalletDaoImpl();
		budgetTransaction = new BudgetDaoImpl();
		transactions      = new ArrayList<Wallet>(walletTransaction.readAll());
		transactionDates  = new ArrayList<String>(budgetTransaction.readTransactionDates());
		
		ListView categoryListView = (ListView) getView().findViewById(R.id.historyListView);
		adapter = new WalletAdapter(transactions, transactionDates, getActivity());
		categoryListView.setAdapter(adapter);
		
		Button reset = (Button) getActivity().findViewById(R.id.clearHistoryButton); 
		reset.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				showActionDialog();
			}
		});
	}
	
	private void showActionDialog() {
		String title   = "Warning";
		String message = "All your history will be deleted, including your current budget amount";
		showAlertDialog(title, message);
	}
	
	private void showAlertDialog(String title, String message) {		
		AlertDialog.Builder alertDialogBuilder = 
			new AlertDialog.Builder(getView().getContext());
		
		alertDialogBuilder.setTitle(title);
		alertDialogBuilder.setMessage(message);
		alertDialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog,int id) {
				getActivity().deleteDatabase("WalletDB");
				transactions.clear();
				adapter.notifyDataSetChanged();
			}
		});
		alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog,int id) {
				dialog.cancel();
			}
		});
		AlertDialog alertDialog = alertDialogBuilder.create();
		alertDialog.show();
	}
}
